package com.lbb.http

import com.google.gson.Gson
import com.google.gson.JsonParser


object GsonUtil {
    private val gson = Gson()
    fun toJson(`object`: Any): String? {
        return gson.toJson(`object`)
    }

    fun <T> toBean(s: String?, cls: Class<T>): T? {
        if (s.isNullOrEmpty()) {
            return null
        }
        try {
            return gson.fromJson(s, cls)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    fun <T> toList(s: String?, cls: Class<T>?): List<T> {
        val list: MutableList<T> = ArrayList()
        try {
            for (jsonElement in JsonParser.parseString(s).asJsonArray) {
                list.add(gson.fromJson(jsonElement, cls))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return list
    }
}